package hotel.quartz.oversea.job.meituan;

import com.alibaba.fastjson.JSON;
import hotel.base.oversea.constant.CommonConstants;
import hotel.base.oversea.constant.CommonUrlConstants;
import hotel.base.oversea.constant.quartz.UrlMtEnums;
import hotel.base.oversea.constant.quartz.UrlSwitchsEnums;
import hotel.base.oversea.utils.GsonUtils;
import hotel.base.oversea.utils.Result;
import hotel.base.oversea.utils.StringUtil;
import hotel.quartz.oversea.config.service.RedisService;
import hotel.quartz.oversea.job.base.BaseJob;
import hotel.quartz.oversea.util.JobRestTemplateUtils;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.quartz.JobExecutionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 * @description: Basic Mt Hotel Info Check Update Job
 * @author: qiuyy
 * @date: 2020-05-26 13:22
 * @version: V1.0
 */
@Slf4j
public class BasicMtHotelInfoCheckUpdateJob implements BaseJob {
    private String timestamp = "Bmhicuj"+String.valueOf(System.currentTimeMillis())+ StringUtil.getFourRandom();

    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private RedisService redisService;

    private void setTimestamp(String timestamp){
        this.timestamp = timestamp;
    }

    @Override
    @SneakyThrows
    public void execute(JobExecutionContext jobExecutionContext) {
        /**
         * 该定时器暂时不用 --》调整为产品校验中  顺便把酒店信息保存
         */


        /*log.info("Basic Mt Hotel Info Check Update Job {} >>>>>>>> 静态酒店信息更新定时器 执行时间: {}", timestamp,DateUtil.getCurrTime());

        if(null != redisService.get("BasicMtHotelInfoCheckUpdateJob_doing")){
            SendUtils.dingMsgNotLog("酒店静态信息跑批，当前程序判断上一个线程还未结束，执行跳过 ","",MessageEnums.genre.GOODS_STATUS_AND_PRICE.getCode(),restTemplate);
            return;
        }
        redisService.setUnit("BasicMtHotelInfoCheckUpdateJob_doing",1,130L, TimeUnit.MINUTES);

        //从缓存中获取上架的酒店
        Long allNeedCheckHotels = redisService.queueSize(MeituanConstants.REDIS_BASIC_HOTELS_INFO_QUEUE_HOTELS);

        Integer saleRoomNum = 0;
        if(allNeedCheckHotels==0){
            log.info("Basic Mt Hotel Info Check Update Job  {} allNeedCheckHotels  当前队列size=0，重新获取缓存上架酒店，首轮重新跑批",timestamp,DateUtil.getCurrTime());
            List<Integer> hotelIdsData = findAscUpMtHotelId();
            if(null != hotelIdsData && hotelIdsData.size()>0){
                for (Integer id:hotelIdsData){
                    redisService.lPush(MeituanConstants.REDIS_BASIC_HOTELS_INFO_QUEUE_HOTELS,Long.valueOf(id));
                }
                allNeedCheckHotels = redisService.queueSize(MeituanConstants.REDIS_BASIC_HOTELS_INFO_QUEUE_HOTELS);
            }else{
                log.error("Basic Mt Hotel Info Check Update Job {} 静态酒店信息更新定时器,未查询到上架酒店信息",timestamp);
            }
        }
        if(null == redisService.get("BasicMtHotelInfoCheckUpdateJob_notFind")){
            if(allNeedCheckHotels<10){
                SendUtils.dingMsgNotLog("[NOT-FIND-HOTELS] 更新酒店静态信息，查询上架酒店产品异常，请核实 ",DateUtil.getCurrTime()+" 查询到数量为："+allNeedCheckHotels,MessageEnums.genre.GOODS_STATUS_AND_PRICE.getCode(),restTemplate);
            }
        }
        log.info("Basic Mt Hotel Info Check Update Job {} 当前获取到 待查询酒店 allNeedCheckHotelsNew：{}",timestamp,allNeedCheckHotels);
        if(allNeedCheckHotels>0){
            int oneCount = 20;
            SendUtils.dingMsgNotLog("[JOB-CHECK] 即将执行，美团酒店静态信息校验 ",DateUtil.getCurrTime()+" 预计耗时："+allNeedCheckHotels/10*(1.5)/60+" 分钟", MessageEnums.genre.GOODS_STATUS_AND_PRICE.getCode(),restTemplate);
            try {
                Thread.sleep(5000);
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
            Long countTask = allNeedCheckHotels/oneCount+1;
            log.info("allNeedCheckHotelsNew countTask={}",countTask);
            Integer sleepTime = 1500;
            for (int i = 0; i < countTask; i++) {
                if(null != redisService.get("BasicMtHotelInfoCheckUpdateJob_stop")){
                    log.info("主动查询停止多线程静态酒店信息更新定时器");
                    break;
                }
                log.info("队列数量：{}",redisService.queueSize(MeituanConstants.REDIS_BASIC_HOTELS_INFO_QUEUE_HOTELS));
                if(redisService.queueSize(MeituanConstants.REDIS_BASIC_HOTELS_INFO_QUEUE_HOTELS)<=oneCount){
                    request(saleRoomNum+"_"+allNeedCheckHotels+"_lastTask");
                }else{
                    request(null);
                }

                if(redisService.queueSize(MeituanConstants.REDIS_BASIC_HOTELS_INFO_QUEUE_HOTELS)==0){
                    log.info("Basic Mt Hotel Info Check Update Job 缓存的酒店为0 break");
                    break;
                }
                if(null != redisService.get("BasicMtHotelInfoCheckUpdateJob_sleep")){
                    sleepTime = (Integer) redisService.get("BasicMtHotelInfoCheckUpdateJob_sleep");
                }
                log.info("Basic Mt Hotel Info Check Update Job 睡眠 sleepTime={}",sleepTime);
                try {
                    Thread.sleep(sleepTime);
                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                }

            }
        }
        redisService.remove("BasicMtHotelInfoCheckUpdateJob_doing");
        log.info("Basic Mt Hotel Info Check Update Job {} >>>>>>>> 静态酒店信息更新定时器 结束时间: {},{}",timestamp,DateUtil.getCurrTime());*/

    }

    private List<Integer> findAscUpMtHotelId() {
        String goods_query_job_up_hotel_data = (String)redisService.get("goods_query_job_up_hotel_data");
        if(null != goods_query_job_up_hotel_data){
            List<Integer> list = GsonUtils.jsonToList(goods_query_job_up_hotel_data,Integer.class);
            log.info("缓存中存在list，goods_query_job_up_hotel_data");
            return list;
        }

        String switchHost = CommonUrlConstants.SWITCHS_ONLINE_HOST;
        String getUpMtHotel = switchHost+ UrlSwitchsEnums.checkFindPriceStatus.GET_UP_MT_HOTEL.getValue();
        log.info("Part Time Query Check Status Job {} 节点时间主动查询上架酒店产品房态定时器 进入方法 findAscUpMtHotelId",timestamp);
        //发起请求
        Map params = new HashMap();
        params.put("timestamp",timestamp);//每次定时器调用接口传唯一timestamp，为了方便查询线程日志
        Result response = JobRestTemplateUtils.post(getUpMtHotel, JSON.toJSONString(params),restTemplate);
        if(response.getCode()== CommonConstants.SUCCESS){
            List<Integer> list = GsonUtils.jsonToList(response.getData().toString(),Integer.class);
            return list;
        }
        return null;
    }
    /**
     * 调用美团接口    主动查询上送的酒店是否存在变动数据，有则接口中操作存入缓存队列
     *
     * @return
     */
    private void request(String ti) {
        String host = CommonUrlConstants.MEITUAN_HOST;
        String url = host+ UrlMtEnums.findUpdateGoods.UPDATE_HOTELS.getValue();
        Map<String,String> map = new HashMap<>();
        if(!ObjectUtils.isEmpty(ti)){
            timestamp = ti+timestamp;
        }
        map.put("timestamp",timestamp);
        log.info("调用更新酒店静态信息前，待保存队列size={}",redisService.queueSize("basic_hotel_save_queue_twenty"));
        Result response = JobRestTemplateUtils.post(url, GsonUtils.GsonString(map),restTemplate);
        if(response.getCode()!= CommonConstants.SUCCESS){
            log.error("静态产品信息定时器 调用美团系统接口失败："+ GsonUtils.GsonString(response));
        }
    }

}
